package com.lr.filter;

import com.lr.entity.User;
import com.lr.mapper.DWMapper;
import com.lr.util.JSONUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.concurrent.TimeUnit;

@WebFilter(urlPatterns = {"*.action","*.auth"})
public class MyFilter implements Filter {
    @Autowired
    private RedisTemplate redisTemplate;
    @Autowired
    private DWMapper dwMapper;
    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
        HttpServletRequest req=(HttpServletRequest)request;
        HttpServletResponse resp=(HttpServletResponse)response;
        //token会话认证
//        String token=req.getParameter("token");
        String token=req.getHeader("token");
        if(token!=null){
            String userJSON=(String) redisTemplate.opsForValue().get(token);
            if(userJSON != null){
                //验证通过，延长token过期时间，为30分钟
                redisTemplate.opsForValue().set(token, userJSON,1800, TimeUnit.SECONDS);
                Integer i;
                if(req.getRequestURI().endsWith(".auth")){
                    if(dwMapper.getSHZTById(dwMapper.getCompanyByUserId(JSONUtil.jsonToObject(userJSON, User.class).getId()).getId())!=2){
                        throw new RuntimeException("no_shzt");
                    }
                }
                chain.doFilter(req, resp);
            }else{
                //resp.sendRedirect(req.getContextPath()+"/index.html");
                throw new RuntimeException("no_token");
            }
        }else{
            throw new RuntimeException("no_token");
        }
    }
}
